layui.use(['layer', 'form', 'table', 'util', 'admin', 'element', 'laydate', 'jquery', 'dropdown'], function () {
    var $ = layui.jquery;
    var layer = layui.layer;
    var form = layui.form;
    var table = layui.table;
    var util = layui.util;
    var admin = layui.admin;
    var element = layui.element;
    var laydate = layui.laydate;
    var dropdown = layui.dropdown;

    //渲染日期组件，如果存在的话
    renderLayDateCp($, laydate);


    //渲染表格
    var userOnlineInsTb = table.render({
        elem: '#userOnlineTable',
        url: prefix + '/list',
        page: true,
        toolbar: ['<p>',
            '<button lay-event="export" class="layui-btn layui-btn-sm layui-bg-cyan icon-btn ' + exportFlag + '"><i class="layui-icon layui-icon-delete"></i>导出记录</button>&nbsp;',
            '</p>'].join(''),
        initSort: {
            field: 'lastAccessTime'
            , type: 'desc'
        },
        where: {
            fieldName: 'lastAccessTime'
            , sortType: 'desc'
        },
        cols: [
            [
                {type: 'numbers'},
                {field: 'sessionId', title: '会话编号', sort: true, width: 200},
                {field: 'loginName', title: '登录账号', sort: true},
                {field: 'deptName', title: '部门名称', sort: true},
                {field: 'ipAddr', title: '主机', sort: true},
                {field: 'loginLocation', title: '登录地点', sort: true},
                {field: 'browser', title: '浏览器', sort: true},
                {field: 'os', title: '操作系统', sort: true},
                {
                    field: 'status', title: '会话状态', sort: true, templet: function (d) {
                        return showDictLabel(dictSysSessionStatus, d.status);
                    }
                },
                {
                    field: 'startTimestamp', title: '登录时间', templet: function (d) {
                        return util.toDateString(d.startTimestamp);
                    }, sort: true
                },
                {
                    field: 'lastAccessTime', title: '最后访问时间', templet: function (d) {
                        return util.toDateString(d.lastAccessTime);
                    }, sort: true
                },
                {title: '操作', toolbar: '#userOnlineTbBar', align: 'center', minWidth: 200}
            ]
        ],
        done: function (res, curr, count) {
            //导出的下拉菜单
            dropdown.render({
                elem: 'button[lay-event=export]'
                , trigger: 'hover'
                , data: [{
                    title: '导出全部（无过滤）'
                    , id: "exportAll"
                }, {
                    title: '导出全部（过滤搜索）'
                    , id: "exportSearch"
                }, {
                    title: '导出当前页数据'
                    , id: "exportCurrent"
                }]
                , click: function (obj) {
                    var id = obj.id;
                    if (id === "exportSearch") {
                        var data = $("#userOnlineTbSearchForm").serializeArray();
                        exportExcel(data);
                    } else if (id === "exportAll") {
                        exportExcel({});
                    } else {
                        exportExcelCurrent(table, res.data);
                    }
                }
            });
        }
    });


//表格搜索
    form.on('submit(userOnlineTbSearch)', function (data) {
        userOnlineInsTb.reload({where: data.field, page: {curr: 1}});
        return false;
    });


//表头工具栏点击事件
    table.on('toolbar(userOnlineTable)', function (obj) {
        var data = table.checkStatus('userOnlineTable').data;
        if (obj.event === "forceLogout") {
            data = data.map(function (item) {
                return item.sessionId;
            });
            deleteData(data);
        }
    });


//表格工具条点击事件
    table.on('tool(userOnlineTable)', function (obj) {
        var data = obj.data;
        if (obj.event === 'forceLogout') {
            deleteData([data.sessionId]);
        }
    });

//触发排序事件
    table.on('sort(userOnlineTable)', function (obj) {
        userOnlineInsTb.reload({
            initSort: obj
            , where: {
                fieldName: obj.field
                , sortType: obj.type
            }
        });
    });


//删除
    function deleteData(data) {
        if (data.length === 0) {
            himio.notice.warn('请选择强退的用户');
            return;
        }
        admin.confirm("确认要强退选中的用户吗?", function (index) {
            layer.close(index);
            var loadIndex = layer.load(2);
            admin.req(prefix + "/batchForceLogout", {
                ids: data.join(",")
            }, function (resp) {
                layer.close(loadIndex);
                himio.notice.resp(resp, function () {
                    location.reload();
                });
                layer.close(index);
            }, "post");
        });
    }

    /* 导出 excel 数据 */
    function exportExcel(data) {
        layer.confirm("确定导出所有在线用户记录数据吗？", function (index) {
            himio.notice.loading("正在导出数据，请稍后...");
            admin.req(prefix + "/export", data, function (result) {
                himio.notice.resp(result, function () {
                    layer.close(index);
                    window.location.href = ctx + "common/download?fileName=" + encodeURI(result.data) + "&delete=" + true;
                    notice.destroy();
                });
            }, "post");
        });
    }

    /* 导出当前页 excel 数据 */
    function exportExcelCurrent(table, exportData) {
        var title = [
            '用户会话id',
            '登录账号',
            '部门名称',
            '登录IP地址',
            '登录地点',
            '浏览器类型',
            '操作系统',
            '在线状态',
            'session创建时间',
            'session最后访问时间',
            '超时时间，单位为分钟'
        ];
        var data = [];
        for (var i = 0; i < exportData.length; i++) {
            data.push([
                exportData[i].sessionId,
                exportData[i].loginName,
                exportData[i].deptName,
                exportData[i].ipAddr,
                exportData[i].loginLocation,
                exportData[i].browser,
                exportData[i].os,
                exportData[i].status,
                exportData[i].startTimestamp,
                exportData[i].lastAccessTime,
                exportData[i].expireTime
            ]);
        }
        table.exportFile(title, data, 'xls');
    }


});
